﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Vigenere_cipher.Models
{
    internal class MyCoder
    {
        /// <summary>
        /// 明文
        /// </summary>
        public string PlainText { get; set; }

        /// <summary>
        /// 密文
        /// </summary>
        public string CipherText { get; set; }

        /// <summary>
        /// 密钥
        /// </summary>
        public string Key { get; set; }
        /// <summary>
        /// 加密程序
        /// </summary>
        public void Ecode()
        {
            //得到密钥长度，按长度分配密钥
            int length = Key.Length;
            //变为数组，方便分配密钥
            char[] plainText = PlainText.ToCharArray();
            char[] key = Key.ToCharArray();
            char[] cipherText = new char[PlainText.Length];
            //加密
            for (int i = 0; i<PlainText.Length; i++)
            {
                int result = (MyFunction(plainText[i])+MyFunction(key[i%length]))%26;
                //将密文形式变为大写字母
                char ch = Convert.ToChar(result+65);
                cipherText[i]=ch;
            }
            CipherText=new string(cipherText);
        }
        public void Dcode()
        {
            //得到密钥长度，按长度分配密钥
            int length = Key.Length;
            //变为数组，方便分配密钥
            char[] cipherText = CipherText.ToCharArray();
            char[] key = Key.ToCharArray();
            char[] plainText = new char[CipherText.Length];
            //解密
            for (int i = 0; i<CipherText.Length; i++)
            {
                int result = MyFunction(cipherText[i])-MyFunction(key[i%length]);
                if (result<0) result+=26;
                //将明文形式变为小写字母
                char ch = Convert.ToChar(result+97);
                plainText[i]=ch;
            }
            PlainText=new string(plainText);
        }

        /// <summary>
        /// 返回字符在字母表中序号，从0开始
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        private int MyFunction(char ch)
        {
            int result = 0;
            //如果为小写
            if (ch>='a'&&ch<='z')
                result= ch-'a';
            //如果为大写
            if (ch>='A'&&ch<='Z')
                result= ch-'A';
            return result;
        }
    }
}
